<?php


namespace app\api\model;
/*
 * 公众号授权登录
 */
class WxLogin{
    protected $_appid;
    protected $_appsecret;
    public function __construct($appid, $appsecret){
        $this->_appid = $appid;
        $this->_appsecret = $appsecret;
    }

    public function getAccesstoken($code){
        $content = $this->_request("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->_appid . "&secret=" . $this->_appsecret . '&code=' . $code . '&grant_type=authorization_code'); //获取access token的json对象
        $content = json_decode($content,true); //进行json解码
        return $content; //返回access token
    }


    public function getUserinfo($access_token, $openid)
    {
        $urlid = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $userInfo = $this->_request($urlid);
        $content = json_decode($userInfo,true); //进行json解码
        return $content;
    }


    public function _request($curl, $https = true, $method = 'get', $data = null, $headers = null)
    {
        $ch = curl_init(); //初始化
        curl_setopt($ch, CURLOPT_URL, $curl); //设置访问的URL
        // curl_setopt($ch, CURLOPT_HEADER, false); //设置不需要头信息
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //只获取页面内容，但不输出
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不做服务器认证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不做客户端认证
        if ($method == 'post') {
            curl_setopt($ch, CURLOPT_POST, true); //设置请求是POST方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //设置POST请求的数据
        }
        $str = curl_exec($ch); //执行访问，返回结果
        curl_close($ch); //关闭curl，释放资源
        return $str;
    }

}
